from alipay import AliPay
from django.http import JsonResponse
from django.shortcuts import render
from django.views import View
from django.conf import settings
# Create your views here.
from order.models import OrderInfo
import os

from payment.models import Payment


class PaymentView(View):
    def get(self, request, pk):
        try:
            order = OrderInfo.objects.get(order_id=pk)
        except:
            return JsonResponse({'error': '订单不存在'}, status=400)
        # print(os.path.join(settings.BASE_DIR, 'apps.payment.keys.app_private_key.pem'))
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,

            app_notify_url=None,  # 默认回调url
            app_private_key_path=os.path.join(settings.BASE_DIR, 'apps/payment/keys/app_private_key.pem'),
            # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            alipay_public_key_path=os.path.join(settings.BASE_DIR, 'apps/payment/keys/alipay_public_key.pem'),
            sign_type="RSA2",  # RSA 或者 RSA2
            debug=settings.ALIPAY_DEBUG  # 默认False
        )

        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=pk,
            total_amount=str(order.total_amount),
            subject='美多商城-%s' % pk,
            return_url=settings.ALIPAY_RETURN_URL,
            # notify_url="https://example.com/notify"  # 可选, 不填则使用默认notify url
        )
        alipay_url = settings.ALIPAY_URL + order_string
        return JsonResponse({'alipay_url': alipay_url, 'code': 0})


class PaymentStatusView(View):
    def get(self, request):
        data = request.GET.dict()
        signature = data.pop("sign")
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,

            app_notify_url=None,  # 默认回调url
            app_private_key_path=os.path.join(settings.BASE_DIR, 'apps/payment/keys/app_private_key.pem'),
            # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            alipay_public_key_path=os.path.join(settings.BASE_DIR, 'apps/payment/keys/alipay_public_key.pem'),
            sign_type="RSA2",  # RSA 或者 RSA2
            debug=settings.ALIPAY_DEBUG  # 默认False
        )
        success = alipay.verify(data, signature)
        if success:
            # 3、保存支付结果
            order_id = data['out_trade_no']
            trade_id = data['trade_no']
            Payment.objects.create(order_id=order_id, trade_id=trade_id)
            # 当前订单状态的修改
            OrderInfo.objects.filter(order_id=order_id, pay_method=2).update(pay_method=3)
            # 4、渲染支付成功页面
            return render(request, 'pay_success.html', {'trade_no': trade_id})
        else:
            return render(request, '404.html')
